package launcher;

import java.io.File;
import java.util.Scanner;

import query.ProximityTerm;
import query.Query;
import query.QueryBuilder;
import query.VectorTerm;

import document.DocumentLibrary;
import document.InvertedIndex;
import document.Stemmer;
import document.StopWordLexicon;

/**
 * Lets the user use the console to ask queries to the system.
 * @author daniel
 *
 */
public class CommandLineQuery {
	
	private static final String DOC_PATH = "TIME" + File.separator + "Docs";


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Reading documents and builing index..\n");
		
		DocumentLibrary library = new DocumentLibrary();
		library.initializeFrom(DOC_PATH);
		InvertedIndex index = new InvertedIndex();
		index.indexLibrary(library);
		
		System.out.println("Indexing completed! Index has the following properties:");
		System.out.println(index.getStatistics(library.getNumbeOfDocuments())+"\n");
		
		askforQuery(index);
		
	}


	private static void askforQuery(InvertedIndex index) {
		System.out.println("Enter a query or 'quit'");
		Scanner keyboard = new Scanner(System.in);
		String input = keyboard.nextLine();
		
		if(input.length()==0) {
			askforQuery(index);
		}
		else if(input.equalsIgnoreCase("quit")) {
			System.out.println("Hasta la vista");;
		}
		else {
			Query q;
			if(input.startsWith("\""))
			{
				String proximity = input.substring(input.indexOf("\"")+1,input.indexOf("$"));
				int n = Integer.parseInt(proximity);
				String query = input.substring(input.indexOf("$")+1);
				q = new ProximityTerm(query, n);
				
			}
			else if(input.startsWith("!"))
			{
				String vectorSpaceString = input.substring(1);
				q = new VectorTerm(vectorSpaceString);
			}
			else
			{
				Stemmer.setDisabled(false);
				StopWordLexicon.setDisabled(false);
				QueryBuilder qb = new QueryBuilder();
				qb.parse(input);
				q = qb.getQuery();
			}
			long startTime = 0;
			long endTime = 0;
			Query opt = q.rebuildOptimal(index);
			Query worst = q.rebuildWorst(index);
			
			startTime = System.nanoTime();
			opt.process(index);
			endTime = System.nanoTime();
			float tOpt = (float) ((endTime-startTime)/1000000.0);
			
			startTime = System.nanoTime();
			worst.process(index);
			endTime = System.nanoTime();
			float tWorst = (float) ((endTime-startTime)/1000000.0);
			
			q.process(index);
			System.out.println(q.getName()+"[best/worst] ["+tOpt+"/"+tWorst+"]"); 
			System.out.println(index.toDocNames(q.getResult()).toString() + "\n");
//			System.out.println("Internal representation:");
//			System.out.println(q.getResult().toString() + "\n");
			askforQuery(index);
		}
		
	}

}
